﻿using System;
using System.Collections.Generic;
using System.Web;

namespace GONES.Tools.Common
{
    public class CWebUserInfo : IUserInfo
    {
        private HttpContext _context;

        public Dictionary<int, long> Grant { get; set; }//权限字典
        private LoginInfo _cloginInfo;
        public LoginInfo CLoginInfo 
        {
            get
            {
                if (_cloginInfo != null)
                    return _cloginInfo;

                if (_context==null ||　_context.Session["LoginInfo"] == null)
                {
                    _cloginInfo = new LoginInfo();
                }
                else
                {
                    _cloginInfo = (LoginInfo)_context.Session["LoginInfo"];
                }
                return _cloginInfo;
            }
        }

        public CWebUserInfo()
        {
            if (HttpContext.Current == null)
                return;

            _context = HttpContext.Current;
        }

        public bool IsOnLine
        {
            get { return !string.IsNullOrEmpty(CLoginInfo.UserName); }
        }

        public void AddGrant(int key, long value)
        {
            if (this.Grant == null)
                Grant = new Dictionary<int, long>();

            Grant.Add(key, value);
        }

        public long GetGrant(int key)
        {
            if (this.Grant == null)
                this.Grant = new Dictionary<int, long>();
            else if (this.Grant.ContainsKey(key))
                return this.Grant[key];

            long l = 0L;
            l = CLoginInfo.Pope[key];
            this.Grant.Add(key, l);

            return l;
        }

        /// <summary>
        /// 权限判断
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public bool TestGrant(int key, long value)
        {
            long grant = this.GetGrant(key);
            if (grant >= 0)
                return ((grant & value) > 0);

            return true;
        }

        /// <summary>
        /// 权限决断
        /// </summary>
        /// <param name="position"></param>
        /// <returns></returns>
        public bool TestGrant(string position)
        {
            if (string.IsNullOrEmpty(position))
                return false;

            string[] ts = position.Split(new char[] { ' ', '\r', '\n', '\t', ',', ';', '|', '/' },
                                         StringSplitOptions.RemoveEmptyEntries);
            if (ts.Length != 2)
                return false;

            int bit;
            int index;
            if (!int.TryParse(ts[0], out index))
                return false;

            if (!int.TryParse(ts[1], out bit))
                return false;

            if (index >= 0 || bit >= 0)
                return this.TestGrant(index, (long) 1 << (bit - 1));

            return true;
        }
    }
}
